package com.kinghood.productcenter.service.base.impl;

import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.kinghood.infrastructure.model.constant.CommonConstants;
import com.kinghood.productcenter.common.model.dao.base.BaseAttributeValueDO;
import com.kinghood.productcenter.common.model.dto.base.ValueListByAttributeIdDTO;
import com.kinghood.productcenter.dao.base.BaseAttributeValueMapper;
import com.kinghood.productcenter.service.base.IBaseAttributeValueService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * <p>
 * 属性可选值 服务实现类
 * </p>
 *
 * @author KingHood
 * @since 2023-12-20
 */
@Service
public class BaseAttributeValueServiceImpl extends ServiceImpl<BaseAttributeValueMapper, BaseAttributeValueDO> implements IBaseAttributeValueService {

    @Override
    public List<ValueListByAttributeIdDTO> getValueListByAttributeId(List<Long> attributeIdList, boolean children) {
        if(CollectionUtils.isEmpty(attributeIdList)){
            return null;
        }
        List<ValueListByAttributeIdDTO> list = new LambdaQueryChainWrapper<>(this.getBaseMapper())
                .in(BaseAttributeValueDO::getAttributeId, attributeIdList)
                .eq(BaseAttributeValueDO::getStatus, CommonConstants.ENABLE)
                .eq(BaseAttributeValueDO::getIsDelete, CommonConstants.IS_DELETE_N)
                .orderByDesc(BaseAttributeValueDO::getSort)
                .list().stream().map(x->{
                    ValueListByAttributeIdDTO one = new ValueListByAttributeIdDTO();
                    BeanUtils.copyProperties(x,one);
                    return one;
                }).collect(Collectors.toList());


        if(children && !CollectionUtils.isEmpty(list)){
            Map<Long, List<ValueListByAttributeIdDTO>> parentMap = list.stream()
                    .filter(x-> Objects.nonNull(x.getParentId()))
                    .collect(Collectors.groupingBy(BaseAttributeValueDO::getParentId));
            list.forEach(x-> x.setChildrenList(parentMap.get(x.getId())));
            return list.stream().filter(x-> Objects.isNull(x.getParentId())).collect(Collectors.toList());
        }

        return list;
    }
}
